import http
import json
from .models import HouseInfo,Area
from django.shortcuts import render
from django.views import View
from django import http
from django.core.paginator import Paginator,EmptyPage
from django.contrib.auth.mixins import LoginRequiredMixin
class IndexView(LoginRequiredMixin,View):
    login_url = '/login/'
    redirect_field_name = 'redict_to'

    def get(self,request):
        area = request.GET.get('area','default')

        page_num = request.GET.get('page')
        if not page_num:
            page_num = 1
        else:
            page_num = int(page_num)
        sort_field = request.GET.get('sort')
        if not sort_field:
            sort_field = 'update_time'
        areas = Area.objects.filter()
        if area == 'default':
            houses = HouseInfo.objects.filter().order_by(sort_field)
            area_name = 'default'
        else:
            try:
                area = Area.objects.get(name=area)
            except:
                return http.HttpResponse('参数错误')
            houses = HouseInfo.objects.filter(jiedao_name=area).order_by(sort_field)
            area_name = area.name
        paginator = Paginator(houses, 5)
        try:
            page_houses = paginator.page(page_num)
        except EmptyPage:
            return http.HttpResponseForbidden('页数出错')
        total_page = paginator.num_pages
        context = {
            'sort': sort_field,  # 排序字段
            'page_houses': page_houses,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码
            'areas':areas,
            'area':area_name,
        }
        return render(request,'index.html',context=context)

# Create your views here.
